<script setup lang="ts">
import { reactive, ref, toRaw } from "vue";
import { Md5 } from "ts-md5";
import { message } from "@/utils/message";
import { type UserInfo, getMine, changePassword } from "@/api/user";
import type { FormInstance, FormRules } from "element-plus";

defineOptions({
  name: "UpdatePassword"
});

const userInfoFormRef = ref<FormInstance>();

const userInfos = reactive({
  currentPassword: "",
  newPassword: "",
  userID: ""
});

const rules = reactive({
  currentPassword: [
    { required: true, message: "原密码不能为空", trigger: "blur" }
  ],
  newPassword: [{ required: true, message: "新密码不能为空", trigger: "blur" }]
});

// 更新信息
const onSubmit = async (formEl: FormInstance) => {
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const { userID, currentPassword, newPassword } = toRaw(userInfos);
      try {
        const params = {
          userID,
          currentPassword: Md5.hashStr(currentPassword),
          newPassword: Md5.hashStr(newPassword)
        };
        const { errCode = -1 } = await changePassword(params);
        if (!errCode) {
          message("修改密码成功", { type: "success" });
        }
      } catch (e) {
        message("修改密码失败", { type: "error" });
      }
    } else {
      message("修改密码失败", { type: "error" });
    }
  });
};

getMine().then(res => {
  Object.assign(userInfos, res.data);
});
</script>

<template>
  <div :class="['bg-bg_color p-[24px]']">
    <h3 class="my-8">修改密码</h3>
    <el-form
      ref="userInfoFormRef"
      class="max-w-[400px]"
      label-position="top"
      :rules="rules"
      :model="userInfos"
    >
      <el-form-item label="当前密码" prop="currentPassword" width="3">
        <el-input
          v-model="userInfos.currentPassword"
          clearable
          type="password"
          placeholder="请输入你的原密码"
          showPassword
        />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input
          v-model="userInfos.newPassword"
          clearable
          type="password"
          placeholder="请输入你的新密码"
          show-password
        />
      </el-form-item>
      <el-button type="primary" @click="onSubmit(userInfoFormRef)">
        保存
      </el-button>
    </el-form>
  </div>
</template>
